import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条 style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

const initialRouters = router.options.routes

router.beforeEach(async(to, from, next) => {
  // start 进度条
  NProgress.start()

  // 设置页面title
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })

      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.userName
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 获取用户信息
          const { roleName } = await store.dispatch('user/getInfo')
          await store.dispatch('GenerateRoutes', {
            roles: [roleName]
          })
          const addRoutesList = store.getters.addRouters
          router.options.routes = [...initialRouters, ...addRoutesList]
          router.addRoutes(addRoutesList) // 动态添加可访问路由表

          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,设置replace: true，这样导航就不会留下历史记录
        } catch (error) {
          Message.warning(error || 'Has Error')
          // 删除令牌，进入登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.warning(error || 'Has Error')
          // next(`/login?redirect=${to.path}`)
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // 免登陆白名单
      next()
    } else {
      // 没有访问权限的其他页面被重定向到登录页面.
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish 进度条
  NProgress.done()
})
